package sad.dao;

import com.db4o.ObjectSet;
import com.db4o.query.Query;
import sad.modelo.Disciplina;
import sad.util.DAOEvent;
import sad.visao.DisciplinaTableModel;

public class AvaliacaoTableDAO extends AbstractDAO {
    
  private static AvaliacaoTableDAO INSTANCE=null;
  private static DisciplinaTableModel tableModel;
  private static Object[] dados;
  
  public static AvaliacaoTableDAO getInstance(){
        if (AvaliacaoTableDAO.INSTANCE ==null){
            AvaliacaoTableDAO.INSTANCE = new AvaliacaoTableDAO();
        }
        return AvaliacaoTableDAO.INSTANCE;
    }
    
  //C(reate)R(etrieve)U(pdate)D(elete)

  public static void create(){
        tableModel = new DisciplinaTableModel();
        Query query = DAO.getObjectContainer().query();
        query.constrain(Disciplina.class);
        query.descend("nome").orderAscending();
        ObjectSet produtoList = query.execute();
    
        while(produtoList.hasNext()) {
            Disciplina proto = (Disciplina)produtoList.next();
            tableModel.addDisciplina(proto);
        }
        tableModel.sortByNome();
  }

    public void addDisciplina(Disciplina p) {
        if (tableModel!=null){
            tableModel.addDisciplina(p);
            tableModel.sortByNome();
        }  
    }

    public DisciplinaTableModel getTableDisciplina() {
        return tableModel;
    }

    public void removeDisciplina(int indexLine) {
        DisciplinaTableDAO.getInstance().delete(tableModel.getDisciplina(indexLine));
        tableModel.removeDisciplina(indexLine);
        
        AvaliacaoTableDAO.getInstance().getSuporteEventos().disparaDAOEvento(
                    new DAOEvent(indexLine, DAOEvent.DAO_DELETE));
    }

    public Object[] isEditable(int indexLine) {
        Disciplina d = tableModel.getDisciplina(indexLine);
        String p = "Sem Professor";
        if(d.getProf()!=null){
            p = d.getProf().getLogin();
        }
        Object[] o = {d.getNome(), d.getAbrev(), p, indexLine}; 
        dados=o;
        return dados;
    }

    public int getIndexDisc() {
        int i= Integer.parseInt(dados[3].toString());
        return i;
    }
    
    public Disciplina getDiscAt(int i) {
        return tableModel.getDisciplina(i);
    }
    
    public void update(Disciplina d, int i){
        
        tableModel.setValueAt(d, i, 0);
        tableModel.setValueAt(d, i, 1);
        tableModel.setValueAt(d, i, 2);
        tableModel.sortByNome();
        AvaliacaoTableDAO.getInstance().getSuporteEventos().disparaDAOEvento(
                    new DAOEvent(tableModel, DAOEvent.DAO_UPDATE));
    }
}